/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.RecommendTopic;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.LazyloadListActivity;
import com.mol.market.common.widget.LoadingDrawable;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 玩家推荐应用列表页
 * 
 * @author andrew.wang
 * @date   2011-9-5
 * @since  Version 0.8
 *
 */
public class RecommendAppsActivity extends LazyloadListActivity implements ApiRequestListener,
        OnItemClickListener {

    // Loading
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;

    private AppListAdapter mAdapter;
    private RecommendTopic mTopic;
    private int mTotalSize;
    
    @Override
    public boolean doInitView(Bundle savedInstanceState) {
        
        setContentView(R.layout.activity_recommend_layout);
        
        mTopic = (RecommendTopic) getIntent()
                .getSerializableExtra(Constants.EXTRA_RECOMMEND_DETAIL);
        initViewsByTheme();
        initActionBar(mTopic);
        
        // 获取玩家评级
        MarketAPI.getMasterRecommendRating(getApplicationContext(), this, mTopic.id);
        
        mList = (ListView) findViewById(android.R.id.list);
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) mLoading.findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) mLoading.findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mList.addHeaderView(createHeaderView(mTopic), null, false);
        mList.setEmptyView(mLoading);
        mList.setItemsCanFocus(false);
        mList.setOnItemClickListener(this);
        lazyload();
        return true;
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();

    }

    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();

    }
    
    @Override
    public void doLazyload() {
        MarketAPI.getMasterRecommendApps(getApplicationContext(), this, getItemsPerPage(),
                getStartIndex(), mTopic.id);
    }


    @Override
    public AppListAdapter doInitListAdapter() {
        
        mAdapter = new AppListAdapter(getApplicationContext(),
                null,
                R.layout.master_recommend_detail_list_item, 
                new String[] { 
                    Constants.KEY_PRODUCT_ICON_URL,
                    Constants.KEY_PRODUCT_NAME, 
                    Constants.KEY_PRODUCT_SUB_CATEGORY,
                    Constants.KEY_PRODUCT_DOWNLOAD,
                    Constants.KEY_PRODUCT_SIZE,
                    Constants.KEY_PRODUCT_SHORT_DESCRIPTION }, 
                new int[] { 
                    R.id.iv_logo, 
                    R.id.tv_name,
                    R.id.tv_category, 
                    R.id.tv_download,
                    R.id.tv_size,
                    R.id.tv_description });
        mAdapter.setProductList();
        return mAdapter;
    }
    
    @Override
    protected int getItemCount() {
        return mTotalSize;
    }
    
    /*
     * 生成推荐主题描述信息（Header）
     */

    private View createHeaderView(RecommendTopic topic) {

        RelativeLayout v = (RelativeLayout) getLayoutInflater().inflate(
                R.layout.master_header_view, mList, false);

        TextView name = (TextView) v.findViewById(R.id.tv_name);
        name.setText(topic.user);

        TextView fans = (TextView) v.findViewById(R.id.tv_fans);
        fans.setText(String.valueOf(topic.fans));

        TextView experience = (TextView) v.findViewById(R.id.tv_experience);

        if (TextUtils.isEmpty(topic.experience)) {
            experience.setVisibility(View.GONE);
        } else {
            experience.setText(mTopic.experience);
        }

        TextView description = (TextView) v.findViewById(R.id.tv_description);
        if (TextUtils.isEmpty(topic.description)) {
            description.setVisibility(View.GONE);
        } else {
            description.setText(topic.description);
        }
        return v;
    }
    
    private void initViewsByTheme() {
        LinearLayout ll = (LinearLayout) findViewById(R.id.action_bar);
        ll.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_BG));
        RelativeLayout rlLeft = (RelativeLayout)ll.findViewById(R.id.action_btn_left);
        rlLeft.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_OPERATION_BG));
        RelativeLayout rlRight = (RelativeLayout)ll.findViewById(R.id.action_btn_right);
        rlRight.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_OPERATION_BG));
        TextView tvLeft = (TextView)ll.findViewById(R.id.tv_left);
        tvLeft.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
        TextView tvRight = (TextView)ll.findViewById(R.id.tv_right);
        tvRight.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
        ImageView splitter = (ImageView) findViewById(R.id.action_splitter);
        splitter.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_ACTION_BAR_SPLITTER));
    }

    /*
     * 用户是否曾经评级过
     */
    private boolean mAlreadyRanked;
    
    
    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {
        
        if (method == MarketAPI.ACTION_GET_RECOMMEND_RATING) {

            mCurrentRank = Utils.getInt((String) obj);
            toogleRankStatus(mCurrentRank);
            if (mCurrentRank != STATUS_UNKNOWN) {
                mAlreadyRanked = true;
            }

        } else if (method == MarketAPI.ACTION_GET_MASTER_RECOMMEND_APPS) {
            HashMap<String, Object> result = (HashMap<String, Object>) obj;

            if (mTotalSize <= 0) {
                mTotalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);
            }

            mAdapter.addDataList((ArrayList<HashMap<String, Object>>) result
                    .get(Constants.KEY_PRODUCT_LIST));

            setLoadResult(true);
        } if (method == MarketAPI.ACTION_ADD_RECOMMEND_RATING) {
            
            mCurrentRank = mPreRank;

            if (mCurrentRank == STATUS_UP) {
                if (mAlreadyRanked) {
                    mTopic.down -= 1;
                }
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_up_success), false);
                mTopic.up += 1;
            } else if (mCurrentRank == STATUS_DOWN) {
                if (mAlreadyRanked) {
                    mTopic.up -= 1;
                }
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_down_success), false);
                mTopic.down += 1;
            }
            toogleRankStatus(mCurrentRank);
            mAlreadyRanked = true;
        }
        
        
    }

    @Override
    public void onError(int method, int statusCode) {

        if (method == MarketAPI.ACTION_ADD_RECOMMEND_RATING) {

            toogleRankStatus(mCurrentRank);

        } else if (method == MarketAPI.ACTION_GET_MASTER_RECOMMEND_APPS) {
            if (statusCode == ApiAsyncTask.BUSINESS_ERROR) {
                // 没有数据
            } else {
                // 超时
                mNoData.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
            }
            setLoadResult(false);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt,
            long paramLong) {

        HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(paramInt
                - mList.getHeaderViewsCount());

        String packageName = (String) item.get(Constants.KEY_PRODUCT_PACKAGE_NAME);
        // 已经安装的产品，点击去详细页
        Intent detailIntent = new Intent(getApplicationContext(),
                com.mol.market.ui_v4.ProductDetailActivity.class);
        detailIntent.putExtra(Constants.EXTRA_PACKAGE_NAME, packageName);
        String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
        detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, name);
        startActivity(detailIntent);
    }
    

    private Handler mHandler = new Handler();
    
    /*
     * 延迟提交，避免用户反复操作
     */

    private Runnable mRankTask = new Runnable() {

        @Override
        public void run() {
            
            if (mCurrentRank == mPreRank) {
                // 用户反复操作，重置回初始状态
                return;
            }
            MarketAPI.addMasterRecommendRating(getApplicationContext(), RecommendAppsActivity.this,
                    mPreRank, mTopic.id);
        }

    };
    
    /*
     * 对专题进行评级
     */
    private void submitRanking() {
        mHandler.removeCallbacks(mRankTask);
        mHandler.postDelayed(mRankTask, 2000);
    }
    
    /*
     * 用户当前对专题的评价
     */
    private int mPreRank;
    
    @Override
    public void onClick(View v) {
        
        super.onClick(v);
        
        int id = v.getId();
        
        switch (id) {
        
        case R.id.no_data:
            // 重试
            mProgress.setVisibility(View.VISIBLE);
            mNoData.setVisibility(View.GONE);
            lazyload();
            return;
            
        case R.id.action_btn_left:
            
            mPreRank = STATUS_UP;
            submitRanking();
            toogleRankStatus(mPreRank);
            return;
            
        case R.id.action_btn_right:
            
            mPreRank = STATUS_DOWN;
            submitRanking();
            toogleRankStatus(mPreRank);
            return;

        default:
            break;
        }
    }
    
    /*
     * 当前的评级状态<br>
     * -1 : 踩
     *  0 : 未评价
     *  1 : 顶
     */
    private int mCurrentRank;
    
    private static final int STATUS_UP = 1;
    private static final int STATUS_DOWN = -1;
    private static final int STATUS_UNKNOWN = 0;
    
    private RelativeLayout mLeftButton;
    private RelativeLayout mRightButton;
    private ImageView mLeftIcon;
    private ImageView mRightIcon;
    private TextView mLeftText;
    private TextView mRightText;
    
    
    /*
     * 切换评级的状态
     */
    private void toogleRankStatus(int rank) {

        switch (rank) {
        case STATUS_UP:
            mLeftButton.setEnabled(false);
            mLeftIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_UP_CHECKED));
            mRightButton.setEnabled(true);
            mRightIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_DOWN));
            break;
            
        case STATUS_UNKNOWN:
            mLeftButton.setEnabled(true);
            mLeftIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_UP));
            mRightButton.setEnabled(true);
            mRightIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_DOWN));
            break;
            
        case STATUS_DOWN:
            mLeftButton.setEnabled(true);
            mLeftIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_UP));
            mRightButton.setEnabled(false);
            mRightIcon.setImageResource(ThemeManager.getResource(mSession, 
                    ThemeManager.KEY_ACTION_BAR_DOWN_CHECKED));
            break;

        default:
            break;
        }
        mLeftText.setText(String.valueOf(mTopic.up));
        mRightText.setText(String.valueOf(mTopic.down));
    }
    
    /*
     * 初始化ActionBar状态
     */
    private void initActionBar(RecommendTopic topic) {

        mLeftButton = (RelativeLayout) findViewById(R.id.action_btn_left);
        mLeftButton.setOnClickListener(this);
        mLeftButton.setEnabled(false);
        mRightButton = (RelativeLayout) findViewById(R.id.action_btn_right);
        mRightButton.setOnClickListener(this);
        mRightButton.setEnabled(false);

        mLeftIcon = (ImageView) findViewById(R.id.iv_left);
        mLeftIcon.setImageResource(R.drawable.action_bar_up_normal);
        mLeftText = (TextView) findViewById(R.id.tv_left);
        mLeftText.setText(String.valueOf(topic.up));
        mRightIcon = (ImageView) findViewById(R.id.iv_right);
        mRightIcon.setImageResource(R.drawable.action_bar_down_normal);
        mRightText = (TextView) findViewById(R.id.tv_right);
        mRightText.setText(String.valueOf(topic.down));
    }
    
}
